package com.cch.android.activity.view;

import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cch.android.activity.ModelLandscapActivity;
import com.cch.android.activity.R;
import com.cch.android.imageutil.ImageUtil;
import com.cch.android.util.Constant;
import com.cch.android.util.MyLog;


public class FrameActivity extends Activity implements OnClickListener{
	 /**
	 * 图片view
	 */
	private ImageView mImageView;
	/**
	 * 初始化的图片
	 */
	private Bitmap mBitmap;
	/**
	 * 变化后的图片
	 */
	private Bitmap bmpSet;
	
	 /**
	 * 所选择图片位置
	 */
	private int mIndex;
	
	private Context context;
	/**
	 * 存放图片 view
	 */
	
	private HashMap<Integer,View> mapView = new HashMap<Integer,View>();
	/**
	 * 标记上次选择 默认第一个
	 */
	private int selectLast=0;
	
	private Button mEditBtn_1,mEditBtn_2,effect_close,effect_save;
	
	private galleryAdapter ba;
	/**
	 * 标示那个button
	 */
	private long initBut;
	
	/**
	 * 图片边框
	 */
	private Bitmap frameBmp=null;
	
	private int[] imageIDs_simple={
			R.drawable.simpleframe_0,R.drawable.simpleframe_1,R.drawable.simpleframe_2,R.drawable.simpleframe_3,
			R.drawable.simpleframe_4,R.drawable.simpleframe_5,R.drawable.simpleframe_6};
	private int[] imageIDs_simple_2={
			R.drawable.format01,R.drawable.format10,R.drawable.format11,R.drawable.format12,
			R.drawable.format13,R.drawable.format14,R.drawable.format17,
			R.drawable.format18,R.drawable.format19,R.drawable.format20,
			R.drawable.format21,R.drawable.format22,R.drawable.format23,
			R.drawable.format24};
	private String[] nameIDs_simple;
	private int[] imageIDs_color={
			R.drawable.colorframe_0,R.drawable.colorframe_1,R.drawable.colorframe_2,R.drawable.colorframe_3,
			R.drawable.colorframe_4,R.drawable.colorframe_5};
	private String[] nameIDs_color={
			"光晕","银河","雪夜","爱心","五角星","七彩色"
			};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.model_setimage_frame);
		context = this;
        Intent intent = getIntent();
        mBitmap = intent.getParcelableExtra("imageBmp");
		initView();
	}

	private void initView() {
		mEditBtn_1 = (Button)findViewById(R.id.setimage1_frame_1);
		mEditBtn_2 = (Button)findViewById(R.id.setimage1_frame_2);
		effect_close = (Button)findViewById(R.id.setimage1_frame_colse);
		effect_save = (Button)findViewById(R.id.setimage1_frame_save);
		initBut = R.id.setimage1_frame_1;
		
		mEditBtn_1.setOnClickListener(this);
		mEditBtn_2.setOnClickListener(this);
		effect_close.setOnClickListener(this);
		effect_save.setOnClickListener(this);
		
		nameIDs_simple= new String[]{
				getString(R.string.frame_a),getString(R.string.frame_b),getString(R.string.frame_c),getString(R.string.frame_d),
				getString(R.string.frame_e),getString(R.string.frame_f),getString(R.string.frame_g)
				};
		
		//编辑图片初始化
		mImageView = ((ImageView) findViewById(R.id.setimage1_frame_image));
		if (mBitmap != null)
			mImageView.setImageBitmap(mBitmap);

		//Gallery 初始化
		UGallery gl = (UGallery) this.findViewById(R.id.Gallery02);
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT, 
                LayoutParams.WRAP_CONTENT);
		lp.setMargins(-(Constant.m_screenWidth/2+150), 0, 0, 0);
		gl.setLayoutParams(lp);
		 ba = new galleryAdapter();

		ba.addDataInt(imageIDs_simple);
		ba.addDataStr(nameIDs_simple);
		gl.setAdapter(ba);
		ba.notifyDataSetChanged();
		gl.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				MyLog.log("上一次选择位置："+selectLast);
				MyLog.log("选择位置："+arg2);
/*					if (frameBmp != null) {
						frameBmp.recycle();
						System.gc();
						frameBmp=null;
					}
*/				switch (arg2) {
				case 0://原图
					mImageView.setImageBitmap(mBitmap);
					break;
	             case 1:
	            	 MyLog.log("选择1");
	            	 frameBmp = ImageUtil.addBigFrame(context,mBitmap,R.drawable.frame_f);
	            	 if (frameBmp != null)
	         			mImageView.setImageBitmap(frameBmp);
					break;
	             case 2:
	            	 frameBmp = ImageUtil.addBigFrame(context,mBitmap,R.drawable.frame_b);
	            	 if (frameBmp != null)
	         			mImageView.setImageBitmap(frameBmp);
	 				break;
	             case 3:
	            	 frameBmp = ImageUtil.addBigFrame(context,mBitmap,R.drawable.frame_c);
	            	 if (frameBmp != null)
	         			mImageView.setImageBitmap(frameBmp);
	 				break;
	             case 4:
	            	 frameBmp = ImageUtil.addBigFrame(context,mBitmap,R.drawable.frame_d);
	            	 if (frameBmp != null)
	         			mImageView.setImageBitmap(frameBmp);
	 				break;
	             case 5:
	            	 frameBmp = ImageUtil.addBigFrame(context,mBitmap,R.drawable.frame_e);
	            	 if (frameBmp != null)
	         			mImageView.setImageBitmap(frameBmp);
	 				break;
	             case 6:
	            	 frameBmp = ImageUtil.addBigFrame(context,mBitmap,R.drawable.frame_a);
	            	 if (frameBmp != null)
	         			mImageView.setImageBitmap(frameBmp);
	 				break;
	             case 7:
	 				break;
	             case 8:
	 				break;
				}
//				Bitmap bmp = addBigFrame(mBitmap,imageIDs_simple_2[arg2]);
//				mImageView.setImageBitmap(bmp);
////				Gallery gl = (Gallery) findViewById(R.id.Gallery01);
//				if(arg2!=0&&selectLast==0)mapView.get(0).setBackgroundResource(R.drawable.effect_0);
//				mapView.get(selectLast).setBackgroundResource(imageIDs_lome[selectLast]);
//				mapView.get(arg2).setBackgroundResource(imageIDs_lome[0]);
////				arg0.setBackgroundResource();
////				gl.setSelection(arg2);
//				selectLast = arg2;
			}
		});

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		
		if (frameBmp != null) {
			frameBmp.recycle();
			System.gc();
			frameBmp=null;
		}
		if (mBitmap != null) {
			mBitmap.recycle();
			System.gc();
			mBitmap=null;
		}
		if (bmpSet != null) {
			bmpSet.recycle();
			System.gc();
			bmpSet=null;
		}
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.setimage1_frame_1:
			if (initBut != R.id.setimage1_frame_1) {
				initBut = R.id.setimage1_frame_1;
				mEditBtn_1.setBackgroundResource(R.drawable.btn_farmeweak_label_c);
				mEditBtn_2.setBackgroundResource(R.drawable.btn_farmeweak_label_a);
				ba.addDataInt(imageIDs_simple);
				ba.addDataStr(nameIDs_simple);
				ba.notifyDataSetChanged();
			}
		
			break;
		case R.id.setimage1_frame_2:
			if (initBut != R.id.setimage1_frame_2) {
				initBut = R.id.setimage1_frame_2;
				mEditBtn_1.setBackgroundResource(R.drawable.btn_farmeweak_label_a);
				mEditBtn_2.setBackgroundResource(R.drawable.btn_farmeweak_label_c);
				ba.addDataInt(imageIDs_color);
				ba.addDataStr(nameIDs_color);
				ba.notifyDataSetChanged();
			}

			break;
		case R.id.setimage1_frame_colse:
//			backToMain();
			finish();
			break;
		case R.id.setimage1_frame_save:
			saveToMain();
			break;
		}
	}
	class galleryAdapter extends BaseAdapter{
		private int[] dataInt;
		private String[] dataStr;
		
		private void addDataInt(int[] dataInt){
			if(this.dataInt!=null)this.dataInt=null;
			this.dataInt = dataInt;
		}
		
		private void addDataStr(String[] dataStr){
			if(this.dataStr!=null)this.dataStr=null;
			this.dataStr = dataStr;
		}

		@Override
		public int getCount() {
			return this.dataInt!=null? this.dataInt.length:0;
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			View view = View.inflate(context, R.layout.modle_setimage_effect_grallery_item, null);
			ImageView galleryImageIv = (ImageView)view.findViewById(R.id.setimage1_effect_gallery_image);
			TextView textIv = (TextView)view.findViewById(R.id.setimage1_effect_gallery_text);
			String textStr = dataStr[arg0];
			LinearLayout.LayoutParams  lp = new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT, 
	                LayoutParams.WRAP_CONTENT);
			if(textStr.length()==2){
			
			    lp.setMargins(20, 0, 0, 0);
			
			}else if(textStr.length()==3){
				
				lp.setMargins(9, 0, 0, 0);
			}else if(textStr.length()>=4){
				lp.setMargins(4, 0, 0, 0);
			}
			
			textIv.setLayoutParams(lp);
			textIv.setText(textStr);
			galleryImageIv.setImageResource(dataInt[arg0]);
			galleryImageIv.setScaleType(ImageView.ScaleType.FIT_XY);
			
			mapView.put(arg0, galleryImageIv);
			
			return view;
		}
		
	}
	/** 
	 * 添加边框 
	 * @param bm 原图片 
	 * @param res 边框资源 
	 * @return 
	 */  
	private Bitmap addBigFrame(Bitmap bm, int res)  
	{  
	    Bitmap bitmap = decodeBitmap(res);  
	    Drawable[] array = new Drawable[2];  
	    array[0] = new BitmapDrawable(bm);  
	    Bitmap b = resize(bitmap, bm.getWidth(), bm.getHeight());  
	    array[1] = new BitmapDrawable(b);  
	    LayerDrawable layer = new LayerDrawable(array);  
	    return drawableToBitmap(layer);  
	}  

	// 放大缩小图片
	private  Bitmap resize(Bitmap bitmap, int w, int h) {
		// 获得原始图片宽高
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		Matrix matrix = new Matrix();
		// 计算缩放比（目标宽高/原始宽高）
		float scaleWidht = ((float) w / width);
		float scaleHeight = ((float) h / height);
		matrix.postScale(scaleWidht, scaleHeight);
		Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
				matrix, true);
		return newbmp;
	}
	/** 
	 * 将Drawable转换成Bitmap 
	 * @param drawable 
	 * @return 
	 */  
	private Bitmap drawableToBitmap(Drawable drawable)  
	{  
	    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);  
	    Canvas canvas = new Canvas(bitmap);  
	    // canvas.setBitmap(bitmap);  
	    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());  
	    drawable.draw(canvas);  
	    return bitmap;  
	}  
	  
	/** 
	 * 将R.drawable.*转换成Bitmap 
	 * @param res 
	 * @return 
	 */  
	private Bitmap decodeBitmap(int res)  
	{  
	    return BitmapFactory.decodeResource(context.getResources(), res);  
	}  
	private void backToMain(){
		Intent intent = new Intent();
		intent.putExtra("imageBmp", mBitmap);
		intent.setClass(this, ModelLandscapActivity.class);
		startActivity(intent);
	}
	/**
	 * 保存到sd卡 回到美化图片主界面
	 */
	private void saveToMain(){
		/*Drawable drawable = mImageView.getDrawable();
		if(drawable!=null)
			try {
				Constant.saveMyBitmap("setImage", 100, drawable);
			} catch (IOException e) {
				e.printStackTrace();
			}*/
		Intent intent = new Intent();
		intent.putExtra("imageBmp", getSetBitmap());
		intent.setClass(this, ModelLandscapActivity.class);
		startActivity(intent);
	}
	/**
	 * 得到处理的图片
	 * @return
	 */
	private Bitmap getSetBitmap(){
		if (mImageView != null) {
			if (bmpSet != null) {
				bmpSet.recycle();
				System.gc();
				bmpSet=null;
			}
			bmpSet = Constant.drawable2Bitmap(mImageView.getDrawable());
			return bmpSet;
		}
		return bmpSet;
	}
}
